import axios from "axios"
import { Notify } from "vant"
import { filterData } from "./specialData"
import { handleData } from "../utils/handleData"
import { getRandomString } from "@/plugins/utils/common"
import forge from "node-forge"
import Setting from "../../setting"
// AES-GCM 的 key（示例，必须是 16/24/32字节）
const secretKeyStr = "MIIBSwIBADCCASsG" // 32字节示例

// 这里不再使用 Web Crypto API，而直接使用 forge
function getCryptoKey() {
  // forge AES密钥直接是一个字节串
  return forge.util.createBuffer(forge.util.encodeUtf8(secretKeyStr.slice(0, 32))).getBytes()
}

// axios.defaults.withCredentials = true; // 允许跨域携带cookie信息
// 创建一个 axios 实例
const service = axios.create({
  baseURL: 'http://8.155.50.173:29190/api/rvic/ic-sharedstation' + Setting.apiBaseURL,
  withCredentials: true,
  crossDomain: true,
  timeout: 30000 // 请求超时时间
})

function geturlparam(url) {
  if (!url) return
  const p = url.split("?")[1]
  return p
}

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (Setting.codeMode === "uapRelease") {
      config.baseURL += sessionStorage.getItem("UAP_ISC_PORT")
    }
    console.log(config.baseURL, "config.baseURL")
    console.log(Setting, "Setting")
    let sign = ""
    let str = ""
    const salt = getRandomString()
    if (config.data && config.method != "get") {
      if (config.url.indexOf("?") > -1) {
        str = decodeURI(geturlparam(config.url))
      }
      const obj = {}
      if (config.data instanceof FormData) {
        // 表单提交
        let hasFile = false
        for (var [key, value] of config.data) {
          if (value instanceof File) {
            hasFile = true
            obj.file = value.fileName
          } else {
            obj[key] = value
          }
        }
        if (hasFile) {
          const arr = Object.keys(obj).sort()
          const sortObj = {}
          arr.forEach((item) => {
            sortObj[item] = obj[item]
          })
          str += JSON.stringify(sortObj) + salt
        } else {
          str += decodeURI(JSON.stringify(obj)) + salt
        }
      } else if (config.data instanceof Array) {
        // data值为数组
        str += JSON.stringify(config.data) + salt
      } else {
        for (var key in config.data) {
          if (config.data[key] instanceof File) {
          } else {
            obj[key] = config.data[key]
          }
        }
        str += JSON.stringify(obj) + salt
      }
    } else if (config.url.indexOf("?") > -1) {
      str = decodeURI(geturlparam(config.url)) + salt
    } else if (config.params) {
      for (const key in config.params) {
        str += key + "=" + config.params[key] + "&"
      }
      str = str ? decodeURI(str.slice(0, -1)) + salt : salt
    } else {
      str = salt
    }
    sign = SG_sm3encrypt(str)
    config.headers.sign = sign
    config.headers.salt = salt
    // 在请求发送之前做一些处理
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    // config.headers['X-Token'] = token;
    config.headers["igw-env"] = Setting.igwEnv // i国网环境标识
    const token = sessionStorage.getItem("token") || ""
    const userid = sessionStorage.getItem("userid") || ""
    config.headers.token = token
    config.headers.userid = userid
    return config
  },
  (error) => {
    // 发送失败
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (Setting.isFilterSpecialCharacters && filterData(response.data)) {
      return false
    } else {
      const token = response.headers.token || ""
      const prevToken = sessionStorage.getItem("token") || ""
      if (!prevToken) {
        sessionStorage.setItem("token", token)
      }
      const dataAxios = response.data
      return handleData(dataAxios)
    }
  },
  (error) => {
    sessionStorage.removeItem("statusCode")
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "请求错误"
          break
        case 401:
          error.message = "未授权，请登录"
          break
        case 403:
          error.message = "拒绝访问"
          break
        case 404:
          error.message = "请求地址出错"
          break
        case 408:
          error.message = "请求超时"
          break
        case 500:
          error.message = "服务器内部错误"
          break
        case 501:
          error.message = "服务未实现"
          break
        case 502:
          error.message = "网关错误"
          break
        case 503:
          error.message = "服务不可用"
          break
        case 504:
          error.message = "网关超时"
          break
        case 505:
          error.message = "HTTP版本不受支持"
          break
        default:
          break
      }
      if (error.message) {
        Notify({ type: "warning", message: error.message })
      }
    } else {
      if (error.code === "ECONNABORTED" || error.message.includes("timeout")) {
        Notify({ type: "warning", message: "当前网络状态不佳" })
      }
    }
    return Promise.reject(error)
  }
)
// 加密
export async function Encrypt(plaintext) {
  const key = getCryptoKey()

  // 12字节IV
  const iv = forge.random.getBytesSync(12)

  const cipher = forge.cipher.createCipher("AES-GCM", key)
  cipher.start({
    iv: iv,
    tagLength: 128 // 16字节
  })
  cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(plaintext)))
  const success = cipher.finish()

  if (!success) {
    throw new Error("加密失败！")
  }

  const ciphertext = cipher.output.getBytes() // 密文
  const tag = cipher.mode.tag.getBytes() // 16字节Tag

  // 拼接iv+ciphertext+tag
  const combined = forge.util.createBuffer()
  combined.putBytes(iv)
  combined.putBytes(ciphertext)
  combined.putBytes(tag)

  // 转Base64
  return forge.util.encode64(combined.getBytes())
}

// 解密
export async function Decrypt(base64Ciphertext) {
  const key = getCryptoKey()

  const combinedBytes = forge.util.decode64(base64Ciphertext)

  // 拆分
  const iv = combinedBytes.slice(0, 12)
  const ciphertext = combinedBytes.slice(12, combinedBytes.length - 16)
  const tag = combinedBytes.slice(combinedBytes.length - 16)

  const decipher = forge.cipher.createDecipher("AES-GCM", key)
  decipher.start({
    iv: iv,
    tag: tag
  })
  decipher.update(forge.util.createBuffer(ciphertext))

  const success = decipher.finish()

  if (!success) {
    throw new Error("解密失败！")
  }

  return forge.util.decodeUtf8(decipher.output.getBytes())
}

export default service
